package main

import (
	"compress/gzip"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"path"
	"strings"
	"time"
)

func getBaiduID() (id string) {
	c := http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				deadline := time.Now().Add(15 * time.Second)
				c, err := net.DialTimeout(netw, addr, 3*time.Second)
				if err != nil {
					return nil, err
				}
				c.SetDeadline(deadline)
				return c, nil
			},
		},
	}
	if resp, err := c.Get("https://www.baidu.com/"); nil == err {
		defer resp.Body.Close()
		if 200 == resp.StatusCode {
			for _, cookie := range resp.Cookies() {
				if "BIDUPSID" == cookie.Name {
					id = cookie.Value
					break
				}
			}
		}
	}
	return
}

func main() {
	var qid string

	flag.Usage = func() {
		fmt.Printf("Usage: %s -i id\n\nOptions:\n", path.Base(os.Args[0]))
		flag.PrintDefaults()
	}

	flag.StringVar(&qid, "i", "", "Question ID.")

	flag.Parse()

	if "" == qid {
		flag.Usage()
	} else {
		for {
			go func(qid string) {
				c := http.Client{
					Transport: &http.Transport{
						Dial: func(netw, addr string) (net.Conn, error) {
							deadline := time.Now().Add(15 * time.Second)
							c, err := net.DialTimeout(netw, addr, 3*time.Second)
							if err != nil {
								return nil, err
							}
							c.SetDeadline(deadline)
							return c, nil
						},
					},
				}
				data := "cm=100669&qid=" + qid + "&aid=2576539934&type=1"
				if req, err := http.NewRequest("POST", "https://zhidao.baidu.com/submit/ajax/", strings.NewReader(data)); nil == err {
					req.Header.Set("Connection", "keep-alive")
					req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36")
					req.Header.Set("Content-Type", "text/plain;charset=UTF-8")
					req.Header.Set("Accept", "*/*")
					req.Header.Set("DNT", "1")
					req.Header.Set("Accept-Encoding", "gzip, deflate, br")
					req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9")
					req.Header.Set("Cookie", "BAIDUID="+getBaiduID())
					if resp, err := c.Do(req); nil == err {
						defer resp.Body.Close()
						if 200 == resp.StatusCode {
							if zr, err := gzip.NewReader(resp.Body); nil == err {
								if _, err := io.Copy(os.Stdout, zr); err != nil {
									log.Fatal(err)
								}
								zr.Close()
							}
						} else {
							fmt.Println("fail")
						}
					} else {
						fmt.Println(err)
					}
				}
			}(qid)
			time.Sleep(3 * time.Second)
		}
	}
}
